Page({
  data: {
    formData: {
      title: '',
      summary: '',
      author: '',
      coverImage: '',
      introduction: '',
      images: []
    },
    currentLength: 0,
    images: [],
    coverImage: '', // 添加封面图片
  },

  // 处理标题输入
  handleTitleInput(e) {
    this.setData({
      'formData.title': e.detail.value
    })
  },

  // 处理摘要输入
  handleSummaryInput(e) {
    this.setData({
      'formData.summary': e.detail.value,
      currentLength: e.detail.value.length
    })
  },

  // 处理作者输入
  handleAuthorInput(e) {
    this.setData({
      'formData.author': e.detail.value
    })
  },

  // 处理介绍输入
  handleIntroInput(e) {
    this.setData({
      'formData.introduction': e.detail.value,
      introLength: e.detail.value.length
    })
  },


  chooseImage() {
    const that = this
    wx.chooseImage({
      count: 8 - that.data.formData.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const app = getApp()
        // 遍历选中的图片逐个上传
        res.tempFilePaths.forEach(filePath => {
          wx.uploadFile({
            url: `${app.globalData.baseUrl}/upload`,
            filePath: filePath,
            name: 'file',
            success(uploadRes) {
              try {
                const data = JSON.parse(uploadRes.data);
                console.log(data)
                if (data.code === 200) {
                  that.setData({
                    'formData.images': [...that.data.formData.images, data.data],
                    images: [...that.data.images, data.data]
                  })
                } else {
                  wx.showToast({
                    title: data.msg || '上传失败',
                    icon: 'none'
                  })
                }
              } catch (error) {
                wx.showToast({
                  title: '上传失败，请更换图片或稍后重试',
                  icon: 'none'
                })
              }
            },
            fail() {
              wx.showToast({
                title: '图片上传失败',
                icon: 'none'
              })
            }
          })
        })
      },
      fail() {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.formData.images
    images.splice(index, 1)
    this.setData({
      'formData.images': images,
      images: images
    })
  },

  previewImage(e) {
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls: this.data.formData.images
    })
  },

  chooseCover() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const filePath = res.tempFilePaths[0];

        that.setData({
          coverImage: filePath
        });
        
        wx.showLoading({
          title: '上传中...',
        });
        const app = getApp()
        wx.uploadFile({
          filePath: filePath,
          name: 'file',
          url: `${app.globalData.baseUrl}/upload`,
          success(uploadRes) {
            wx.hideLoading();
            try {
              // 添加状态码检查
              if (uploadRes.statusCode === 413) {
                wx.showModal({
                  title: '上传失败',
                  content: '上传的图片太大了，请选择小于1MB的图片',
                  showCancel: false
                });
                return;
              }
              
              const data = JSON.parse(uploadRes.data);
              console.log(data);
              if (data.code === 200) {
                that.setData({
                  "formData.coverImage": data.data
                });
                wx.showToast({
                  title: '封面上传成功',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: '封面上传失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('数据解析错误:', error);
              // 检查是否是因为图片太大导致的错误
              if (uploadRes.statusCode === 413) {
                wx.showModal({
                  title: '上传失败',
                  content: '上传的图片太大了，请选择小于1MB的图片',
                  showCancel: false
                });
              } else {
                wx.showToast({
                  title: '上传失败，请重试',
                  icon: 'none'
                });
              }
            }
          },
          fail(err) {
            wx.hideLoading();
            if (err.statusCode === 413) {
              wx.showModal({
                title: '上传失败',
                content: '上传的图片太大了，请选择小于1MB的图片',
                showCancel: false
              });
            } else {
              wx.showToast({
                title: '封面上传失败',
                icon: 'none'
              });
            }
          }
        });
      },
      fail() {
        wx.showToast({
          title: '选择封面失败',
          icon: 'none'
        });
      }
    });
  },
  deleteCover() {
    this.setData({
      'formData.coverImage': '',
      coverImage: ''
    })
  },

  previewCover() {
    if (this.data.formData.coverImage) {
      wx.previewImage({
        urls: [this.data.formData.coverImage]
      })
    }
  },

  async handleSubmit() {
    try {
      // 添加提交确认对话框
      const confirmResult = await new Promise((resolve, reject) => {
        wx.showModal({
          title: '确认发布',
          content: '确定发布活动成果吗？',
          success: (res) => {
            if (res.confirm) {
              resolve(true);
            } else {
              resolve(false);
            }
          },
          fail: reject
        });
      });
  
      // 如果用户取消，则直接返回
      if (!confirmResult) {
        return;
      }
  
      const { images } = this.data;
      const updatedFormData = { ...this.data.formData };
    
      images.forEach((image, index) => {
        const key = `image${index + 1}`;
        updatedFormData[key] = image;
      });
    
      await this.setData({
        formData: updatedFormData
      });
    
      const app = getApp();
      const result = await app.activityApi.outComes(this.data.formData);
    
      if (result.data.code === 200) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1500
        });
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
            success: () => {
              console.log('跳转成功');
            },
            fail: (err) => {
              console.error('跳转失败', err);
            }
          });
        }, 2000);
      } else {
        throw new Error(result.data.msg || '提交失败');
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '提交失败',
        icon: 'none'
      });
    }
  },
  // 上传单个文件的方法
  uploadFile(filePath) {
    return new Promise((resolve, reject) => {
      const app = getApp()
      // 创建FormData对象
      const formData = new FormData()
      formData.append('file', filePath)

    })
  }
})